<template>
  <div v-if="loading">
    <el-skeleton :rows="5" animated />
  </div>
  <div v-else>
    <div>
      <el-input
        v-model="emailContents"
        style="width: 400px; margin-bottom: 25px"
        :autosize="{ minRows: 3, maxRows: 7 }"
        type="textarea"
        placeholder="请输入邮件正文"
      />
    </div>
    <div style="margin-bottom: 15px">
      <el-select-v2
        v-model="selectValue"
        style="width: 240px; margin-right: 10px"
        filterable
        remote
        :remote-method="userSelecterRemoteMethod"
        clearable
        :options="selecterOptions"
        :loading="userSelecterLoading"
        placeholder="请输入需添加的用户"
      />
      <el-button @click="addUserToNoteList">添加</el-button>
    </div>
    <el-table
      table-layout="fixed"
      ref="multipleTableRef"
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column property="userName" label="用户" width="120" />
      <el-table-column
        property="email"
        label="邮箱"
        width="300"
        show-overflow-tooltip
      />
      <el-table-column property="noteCount" label="通知次数" />
      <el-table-column property="blameCount" label="指摘数" />
    </el-table>
  </div>
</template>

<script lang="ts" setup>
import {
  ref,
  defineExpose,
  defineProps,
  onMounted,
  getCurrentInstance,
  nextTick,
} from "vue";
import { ElTable } from "element-plus";
import { ElMessage } from "element-plus";
import { ElLoading } from "element-plus";
import { ElMessageBox } from "element-plus";

const instance = getCurrentInstance();
const { $http } = instance?.appContext.config.globalProperties as any;
const props = defineProps({
  uid: {
    type: String,
    required: true,
  },
});

interface BlameIntroducer {
  userId: string;
  userName: string;
  email: string;
  noteCount: number;
  blameCount: number;
}
interface ListItem {
  value: string;
  label: string;
  validValue: string;
  userInfo: UserInfo;
}

interface UserInfo {
  userId: string;
  userName: string;
  email: string;
  displayName: string;
  pinyin: string;
}
const selectValue = ref({});
const itemList = ref<ListItem[]>([]);
const users = ref<UserInfo[]>([]);
const selecterOptions = ref<ListItem[]>([]);
const loading = ref(false);
const sending = ref(false);
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<BlameIntroducer[]>([]);
const userSelecterLoading = ref(false);
const tableData = ref<BlameIntroducer[]>([]);
const emailContents = ref("");

const toggleSelection = (rows?: BlameIntroducer[]) => {
  if (rows) {
    rows.forEach((row) => {
      // TODO: improvement typing when refactor table
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      multipleTableRef.value!.toggleRowSelection(row, undefined);
    });
  } else {
    multipleTableRef.value!.clearSelection();
  }
};

const addUserToNoteList = () => {
  console.log("将以下用户添加到通知列表");
  console.log(selectValue.value);
  //找到这个显示值所对应的用户
  let targetUser = users.value.find(
    (user) => user.displayName === selectValue.value
  );
  if (!targetUser) {
    ElMessage({
      type: "error",
      message: "用户获取失败",
    });
    return;
  }
  if (!targetUser.email) {
    ElMessage({
      type: "error",
      message: "用户 ${targetUser.displayName} 未配置邮箱",
    });
    return;
  }
  console.log(targetUser);
  const newBlameIntroducer: BlameIntroducer = {
    userId: targetUser.userId,
    userName: targetUser.userName,
    email: targetUser.email,
    noteCount: 0, // 假设noteCount默认为0
    blameCount: 0, // 假设blameCount默认为0
  };
  tableData.value.push(newBlameIntroducer);
  nextTick(() => {
    multipleTableRef.value.toggleRowSelection(
      tableData.value[tableData.value.length - 1],
      true
    );
  });
};

const loadData = () => {
  loading.value = true;
  $http
    .get("/getBlameIntroducers?uid=" + props.uid)
    .then((response: { data: BlameIntroducer[] }) => {
      console.log("指摘提交者查询结果", response.data);
      loading.value = false;
      tableData.value = response.data;
      nextTick(() => {
        selectAll();
      });
    })
    .catch((error: any) => {
      console.log(error);
      loading.value = false;
      ElMessage({
        type: "error",
        message: error,
      });
    });
};

const selectAll = () => {
  multipleTableRef.value.toggleAllSelection(true);
};

const handleSelectionChange = (val: BlameIntroducer[]) => {
  multipleSelection.value = val;
};

const userSelecterRemoteMethod = async (query: string) => {
  if (query !== "") {
    //userSelecterLoading.value = true;
    try {
      await initUserList();
      selecterOptions.value = itemList.value.filter((item) => {
        return item.validValue.toLowerCase().includes(query.toLowerCase());
      });
    } catch (error) {
      console.error(error);
      ElMessage({
        type: "error",
        message: error,
      });
    }
  } else {
    selecterOptions.value = [];
  }
};

const initUserList = async () => {
  try {
    userSelecterLoading.value = true;
    if (itemList.value == null || itemList.value.length == 0) {
      const response = await $http.get("/getAllUsers");
      console.log("init user completed");
      console.log(response.data);
      users.value = response.data;
      itemList.value = users.value.map((item): ListItem => {
        return {
          value: `${item.displayName}`,
          label: `${item.displayName}`,
          validValue: `${item.displayName}` + item.pinyin,
          userInfo: item,
        };
      });
    }
  } catch (error) {
    console.error(error);
    ElMessage({
      type: "error",
      message: error,
    });
  } finally {
    userSelecterLoading.value = false;
  }
};

const sendEmail2Sels = async () => {
  sending.value = true;
  const elloading = ElLoading.service({
    lock: true,
    text: "邮件发送中，请稍后...",
    background: "rgba(0, 0, 0, 0.7)",
  });

  try {
    const sendEmailToBlameIntroducerUrl = "/sendEmailToBlameIntroducer";
    const userIds = multipleSelection.value.map((item) => item.userId);
    let requestData = {
      uid: props.uid,
      userIds: userIds,
      contents: emailContents.value,
    };
    console.log("保存主表单数据：", requestData);
    const response1 = await $http.post(
      sendEmailToBlameIntroducerUrl,
      requestData
    );
    console.log("提交结果", response1.data);
    ElMessage({
      type: "success",
      message: "发送成功",
    });
    loadData();
  } catch (error) {
    console.log(error);
    ElMessage({
      type: "error",
      message: error,
    });
  } finally {
    sending.value = false;
    elloading.close();
  }

  // //模拟发送邮件请求
  // setTimeout(() => {
  //   ElMessage({
  //     type: "success",
  //     message: "邮件通知成功",
  //   });
  //   sending.value = false;
  //   elloading.close();
  //   //模拟发送邮件成功后的重新加载
  //   loading.value = true;
  //   setTimeout(() => {
  //     loading.value = false;
  //   }, 2000);
  // }, 2000);
};

//TODO 发送邮件请求
const sendEmail2SelsCondition = () => {
  let hasSendedUser = false;
  console.log("给以下用户发送邮件");
  multipleSelection.value.forEach((sel: BlameIntroducer) => {
    console.log("--->" + JSON.stringify(sel));
    console.log("--->" + sel.email);
    if (sel.noteCount > 0) {
      hasSendedUser = true;
    }
  });

  //如果邮件发送数量大于一，则提示一下
  if (hasSendedUser) {
    ElMessageBox.confirm("所选用户已发送过通知，是否继续发送？", "提示", {
      confirmButtonText: "是",
      cancelButtonText: "否",
      type: "info",
    })
      .then(() => {
        sendEmail2Sels();
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消发送",
        });
      });
  } else {
    sendEmail2Sels();
  }
};

onMounted(() => {
  loadData();
  selectAll();
});

defineExpose({
  sendEmail2Selection: sendEmail2SelsCondition,
});
</script>
